package com.training.schedule_management_system_admin.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.training.schedule_management_system_admin.entity.Schedule;
import com.training.schedule_management_system_admin.entity.Scheduleframework;
import com.training.schedule_management_system_admin.entity.Scheduletable;
import com.training.schedule_management_system_admin.entity.User;
import com.training.schedule_management_system_admin.service.ScheduleServce;
import com.training.schedule_management_system_admin.service.ScheduleframeworkService;
import com.training.schedule_management_system_admin.service.ScheduletableService;
import com.training.schedule_management_system_admin.service.ShareService;
import com.training.schedule_management_system_admin.utils.DateListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/share")
public class ShareController {

    @Autowired
    ScheduleframeworkService scheduleframeworkService;

    @Autowired
    ShareService shareService;

    @Autowired
    ScheduletableService scheduletableService;

    @Autowired
    ScheduleServce scheduleServce;

    /*
    日程框架发布/关闭
    */
    @RequestMapping("/publish/{scheduleframeworkId}")
    public String publish(@PathVariable("scheduleframeworkId")Integer scheduleframeworkId,
                          @RequestParam(value = "flag")String flag, Model model, HttpSession session){
        JSONObject jsonObject=new JSONObject();
        Scheduleframework framework= scheduleframeworkService.getFrameworkAndTerm(scheduleframeworkId);
        if(framework==null){
            jsonObject.put("msg","该日程框架不存在!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        //不能发布/关闭其它用户的日程框架!
        if(!framework.getUserId().equals(((User) session.getAttribute("loginUser")).getId())){
            jsonObject.put("msg", "该日程框架不存在!");
            model.addAttribute("result", jsonObject);
            return "/user/result";
        }
        boolean b = Boolean.parseBoolean(flag);
        if (b){//flag=true，发布
            if(framework.getPublishState()==1){
                jsonObject.put("msg","该日程框架已发布，无需重复操作!");
                model.addAttribute("result",jsonObject);
                return "/user/result";
            }
            framework.setDraftState(0);
            framework.setPublishState(1);
            scheduleframeworkService.state(framework);
            jsonObject.put("msg","该日程框架已成功发布!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }else {//flag=flase，关闭
            if(framework.getShareState()==1){
                jsonObject.put("msg","该日程框架已开放共享!请先取消共享再操作!");
                model.addAttribute("result",jsonObject);
                return "/user/result";
            }
            if(framework.getDraftState()==0 && framework.getPublishState()==0){
                jsonObject.put("msg","该日程框架已关闭，无需重复操作!");
                model.addAttribute("result",jsonObject);
                return "/user/result";
            }
            framework.setDraftState(0);
            framework.setPublishState(0);
            scheduleframeworkService.state(framework);
            jsonObject.put("msg","该日程框架已成功关闭!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
    }

    /*
    日程框架共享
     */
    @RequestMapping("/share/{scheduleframeworkId}")
    public String share(@PathVariable("scheduleframeworkId")Integer scheduleframeworkId,
                        @RequestParam(value = "flag")String flag,Model model,HttpSession session){
        JSONObject jsonObject=new JSONObject();
        Scheduleframework framework= scheduleframeworkService.getFrameworkAndTerm(scheduleframeworkId);
        if(framework==null){
            jsonObject.put("msg","该日程框架不存在!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        //不能开放/取消共享其它用户的日程框架!
        if(!framework.getUserId().equals(((User) session.getAttribute("loginUser")).getId())){
            jsonObject.put("msg", "该日程框架不存在!");
            model.addAttribute("result", jsonObject);
            return "/user/result";
        }
        if(framework.getPublishState()==0 ){
            jsonObject.put("msg","该日程框架还未发布!必须先发布才能共享!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        boolean b = Boolean.parseBoolean(flag);
        if(b){//flag=true，共享
            if(framework.getShareState()==1){
                jsonObject.put("msg","该日程框架已开放共享，无需重复操作!");
                model.addAttribute("result",jsonObject);
                return "/user/result";
            }
            framework.setShareState(1);
            framework.setShareId(UUID.randomUUID().toString());
            scheduleframeworkService.state(framework);
            jsonObject.put("msg","该日程框架已开放共享!");
            jsonObject.put("shareId","http://localhost:8088/share/shareId/"+framework.getShareId());
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }else{//取消共享
            if(framework.getShareState()==0){
                jsonObject.put("msg","该日程框架已取消共享，无需重复操作!");
                model.addAttribute("result",jsonObject);
                return "/user/result";
            }
            framework.setShareState(0);
            scheduleframeworkService.state(framework);
            jsonObject.put("msg","该日程框架已取消共享!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
    }

    /*
    通过共享链接访问查看日程框架
     */
    @RequestMapping("/shareId/{shareId}")
    public String shareId(@PathVariable("shareId")String shareId,Model model){
        JSONObject  jsonObject=new JSONObject();
        Scheduleframework framework=scheduleframeworkService.getByShareId(shareId);
        if(framework==null){
            jsonObject.put("msg","该日程框架不存在!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        if(framework.getShareState()==0 || framework.getShareId()==null || "".equals(framework.getShareId())){
            jsonObject.put("msg","该日程框架未开放共享或该共享链接已过期!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        Scheduleframework result = scheduleframeworkService.getFrameworkAndTerm(framework.getId());
        jsonObject.put("result",result);
        String startDate = DateUtil.format(result.getStartDate(),"yyyy-MM-dd");
        String endDate = DateUtil.format(result.getEndDate(),"yyyy-MM-dd");
        List<String> days = DateListUtils.getDays(startDate, endDate);
        jsonObject.put("days",days);
        jsonObject.put("size",days.size());
        model.addAttribute("msg",jsonObject);
        return "/user/scheduleframework_view";
    }

    /*
    日程框架复制
     */
    @RequestMapping("/copy/{scheduleframeworkId}")
    public String copyFramework(@PathVariable("scheduleframeworkId")Integer scheduleframeworkId,Model model){
        JSONObject jsonObject=new JSONObject();
        Scheduleframework framework= scheduleframeworkService.getFrameworkAndTerm(scheduleframeworkId);
        if(framework==null){
            jsonObject.put("msg","该日程框架不存在!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        scheduleframeworkService.copy(framework);
        jsonObject.put("msg","复制成功!已保存为草稿状态，可在日程框架页查看!");
        model.addAttribute("result",jsonObject);
        return "/user/result";
    }

    /*
    日程表复制
     */
    @RequestMapping("/copyTable/{scheduletableId}")
    public String copyTable(@PathVariable("scheduletableId")Integer scheduletableId,Model model){
        JSONObject jsonObject=new JSONObject();
        Scheduletable table = scheduletableService.getTableById(scheduletableId);
        if(table==null){
            jsonObject.put("msg","该日程表不存在!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        List<Schedule> schedules = scheduleServce.getAllByTableId(table.getId());
        if(schedules!=null && !schedules.isEmpty()){
            table.setSchedules(schedules);
        }
        scheduletableService.copy(table);
        jsonObject.put("msg","复制成功!已保存为私有状态，可在日程表页查看!");
        model.addAttribute("result",jsonObject);
        return "/user/result";
    }

    /*
    用户共享社区
     */
    @RequestMapping("/community")
    public String community(Model model){
        JSONObject jsonObject=new JSONObject();

        //获取所有的用户已开放共享的日程框架
        List<User> users1=shareService.getAllFramework();
        jsonObject.put("users1",users1);

        //获取所有的用户已公开的日程表
        List<User> users2 = shareService.getAllTable();
        jsonObject.put("users2",users2);

        model.addAttribute("msg",jsonObject);
        return "/user/community";
    }

    /*
    日程表公开/私有
    */
    @RequestMapping("/open/{scheduletableId}")
    public String open(@PathVariable("scheduletableId")Integer scheduletableId,
                          @RequestParam(value = "flag")String flag,Model model,HttpSession session){
        JSONObject jsonObject=new JSONObject();
        Scheduletable table=scheduletableService.getTableById(scheduletableId);
        if(table==null){
            jsonObject.put("msg","该日程表不存在!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
        //不能公开/私有其它用户的日程表!
        if(!table.getUserId().equals(((User) session.getAttribute("loginUser")).getId())){
            jsonObject.put("msg", "该日程表不存在!");
            model.addAttribute("result", jsonObject);
            return "/user/result";
        }
        boolean b = Boolean.parseBoolean(flag);
        if (b){//flag=true，公开
            if(table.getOpenState()==1){
                jsonObject.put("msg","该日程表已设置为公开，无需重复操作!");
                model.addAttribute("result",jsonObject);
                return "/user/result";
            }
            table.setOpenState(1);
            scheduletableService.state(table);
            jsonObject.put("msg","该日程表已成功设置为公开!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }else {//flag=flase，私有
            if(table.getOpenState()==0){
                jsonObject.put("msg","该日程表已置为私有，无需重复操作!");
                model.addAttribute("result",jsonObject);
                return "/user/result";
            }
            table.setOpenState(0);
            scheduletableService.state(table);
            jsonObject.put("msg","该日程表已成功设置为私有!");
            model.addAttribute("result",jsonObject);
            return "/user/result";
        }
    }

    /*
    日程表查询
    */
    @RequestMapping("/searchTable")
    public String searchTable(@RequestParam(value = "pageNum",defaultValue ="1") int pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "500") int pageSize,
                              @RequestParam(value = "navigatePages",defaultValue = "5") int navigatePages,
                              String value,Model model){
        JSONObject jsonObject=new JSONObject();
        PageHelper.startPage(pageNum, pageSize);
        List<Scheduletable> scheduletables=shareService.findOpenTableLike(value);
        if( scheduletables.isEmpty()){
            jsonObject.put("msg","没有找到包含该名字的日程表");
            model.addAttribute("table_result",jsonObject);
            return "/user/search";
        }
        PageInfo page=new PageInfo(scheduletables,navigatePages);
        jsonObject.put("page",page);
        model.addAttribute("msg_table",jsonObject);
        return "/user/search";
    }

    /*
    日程框架查询
     */
    @RequestMapping("/searchFramework")
    public String searchFramework(@RequestParam(value = "pageNum",defaultValue ="1") int pageNum,
                                  @RequestParam(value = "pageSize",defaultValue = "500") int pageSize,
                                  @RequestParam(value = "navigatePages",defaultValue = "5") int navigatePages,String value,Model model){
        JSONObject jsonObject=new JSONObject();
        PageHelper.startPage(pageNum, pageSize);
        List<Scheduleframework> scheduleframeworks=shareService.findShareFrameworkLike(value);
        if(scheduleframeworks.isEmpty()){
            jsonObject.put("msg","没有找到包含该名字的日程框架");
            model.addAttribute("framework_result",jsonObject);
            return "/user/search";
        }
        PageInfo page=new PageInfo(scheduleframeworks,navigatePages);
        jsonObject.put("page",page);
        model.addAttribute("msg_framework",jsonObject);
        return "/user/search";
    }
}
